package com.learn.annotation_config.bean;

import com.alibaba.druid.pool.DruidDataSource;
import com.learn.annotation_config.bean.beans.dao.UserDao;
import com.learn.annotation_config.bean.beans.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

// @Component：包含@Bean注解和工厂方法的类必须被Spring容器管理
@Component
public class ThirdBeans {
    // @Bean：指定name属性、Bean实例化后执行的初始化方法、Bean实例销毁前执行的方法
    @Bean(
            name = "userService",
            initMethod = "init",
            destroyMethod = "destroy"
    )
    public UserServiceImpl userService() {
        return new UserServiceImpl();
    }
    
    // @Bean：如果不指定name属性，默认将方法名名作为该Bean的名称
    // @Value：形参前用于注入普通数据
    @Bean
    public DruidDataSource dataSource(
            @Value("com.mysql.jdbc.Driver") String driverClassName,
            @Value("jdbc:mysql://localhost:3306/learn_sql") String url,
            @Value("${my-app.username}") String username,
            @Value("${my-app.password}") String password
    ) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    
    // @Bean：指定name属性
    // @Autowired：形参前用于注入引用数据，@Autowired可省略
    // @Autowired+@Primary：形参前用于注入引用数据，@Autowired可省略
    // @Autowired+@Qualifier：形参前用于注入引用数据，@Autowired可省略
    // @Autowired：用于List上时，表示注入所有接口的实现类，@Autowired可省略
    @Bean(name = "formatDate")
    public Date date(
            @Autowired UserDao userDao2,
            @Autowired UserDao userDaoPrimary,
            @Qualifier("userDao1") UserDao userDaoQualifier,
            List<UserDao> userDaoList
    ) throws ParseException {
        System.out.println("userDao2:" + userDao2); // 2
        System.out.println("userDaoPrimary:" + userDaoPrimary); // 2
        System.out.println("userDaoQualifier:" + userDaoQualifier); // 1
        System.out.println("userDaoList:" + userDaoList); // [1, 2]
        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.parse("2025-02-19 12:00:00");
    }
}
